from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from app.config import config_map
from app.utils.common import ReConverter
from flask_wtf import CSRFProtect
import logging
from logging.handlers import RotatingFileHandler

db = SQLAlchemy()

# 配置日志
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
rotating_handler = RotatingFileHandler(filename="logs/log.txt", maxBytes=1024*1024, backupCount=10)
logging.getLogger().addHandler(rotating_handler)

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_map.get(config_name))

    # 使用app初始化db
    db.init_app(app)

    # 为flask补充csrf防护
    CSRFProtect(app)

    # 为flask添加自定义的转换器
    app.url_map.converters["re"] = ReConverter

    # 注册接口蓝图
    from app import api_v1
    api_v1.register_blueprint(app)

    # 注册静态资源蓝图
    from app.web_html import html
    app.register_blueprint(html)

    with app.app_context():
        from app.models import UserModel, AreaModel, DeviceModel, OrderModel, HouseModel
        
        ''' 数据初始化 '''
        # db.drop_all()
        # db.create_all()
        # from .test_data import init_table
        # init_table(db)

    return app